package com.aramis.mydytt.ui.search

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.aramis.mydytt.R
import com.aramis.mydytt.ui.base.BaseFragment
import com.aramis.mydytt.ui.common.CommonMovieItemAdapter
import com.aramis.mydytt.ui.detail.MovieDetailActivity
import com.aramis.mydytt.ui.search.fragment.SearchTagFragment
import com.aramis.mydytt.widget.LoadingStateView

/**
 * 推荐Fragment
 */
class MainSearchFragment : BaseFragment() {
    private lateinit var mainSearchViewModel: MainSearchViewModel
    private val commonMovieItemAdapter = CommonMovieItemAdapter()
    private var loadingView: LoadingStateView? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mainSearchViewModel = createViewModel()
        val root = inflater.inflate(R.layout.fragment_main_search, container, false)
        initView(root)
        observerData()
        initData()
        return root
    }

    private fun initData() {
        mainSearchViewModel.getSearchResultDefault()
    }

    private fun observerData() {
        mainSearchViewModel.searchResultData.observe(viewLifecycleOwner, {
            loadingView?.showState(it)
            commonMovieItemAdapter.setData(it)
        })
    }

    private fun initView(root: View) {
        root.findViewById<View>(R.id.search_bar_main).setOnClickListener {
            startActivity(Intent(requireActivity(), SearchResultActivity::class.java))
        }
        val searchTagFragment = SearchTagFragment()
        searchTagFragment.onSearchTagClickListener = { cate, area, year, type, sort ->
            mainSearchViewModel.getSearchResult(cate, area, year, type, sort)
        }
        parentFragmentManager.beginTransaction().add(R.id.container_search_tag, searchTagFragment).commit()
        val recyclerView = root.findViewById<RecyclerView>(R.id.list_search)
        recyclerView.adapter = commonMovieItemAdapter
        commonMovieItemAdapter.onItemClickListener = {
            MovieDetailActivity.start(requireActivity(), it)
        }
        recyclerView.layoutManager = GridLayoutManager(requireContext(), 3)
        loadingView = root.findViewById(R.id.view_loading)
        loadingView?.setOnErrorRetryListener { initData() }
    }
}